package com.example.onlinemusic.controller;

import com.example.onlinemusic.mapper.LoveMusicMapper;
import com.example.onlinemusic.mapper.MusicMapper;
import com.example.onlinemusic.model.Music;
import com.example.onlinemusic.model.User;
import com.example.onlinemusic.tools.Constant;
import com.example.onlinemusic.tools.ResponseBodyMessage;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import jakarta.validation.Valid;
import org.apache.ibatis.binding.BindingException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/music")
public class MuscicController {
    @Value("${music.local.path}")  // 注意：使用点号连接层级，无需换行
    private String SAVE_PATH;
    @Autowired
    private MusicMapper musicMapper;
    @Autowired
    private LoveMusicMapper loveMusicMapper;
    @RequestMapping("/upload")
    public ResponseBodyMessage<Boolean> musicUpload(@RequestParam String singer,
                                                    @RequestParam("filename") MultipartFile file,
                                                    HttpServletRequest request,
                                                    HttpServletResponse resp){
        //1.检查是否登录
        HttpSession httpSession=request.getSession(false);
        if(httpSession==null||httpSession.getAttribute(Constant.USERINFO_SESSION_KEY)==null){
            System.out.println("没有登录");
            return  new ResponseBodyMessage<>(101,"请登录后上传音乐文件！",false);
        }

        String fileNameAndType=file.getOriginalFilename();
        System.out.println("fileNameAndType:" + fileNameAndType);
        String path=SAVE_PATH+fileNameAndType;
        File dest=new File(path);
        if(!dest.exists()){
            dest.mkdir();
        }
        try {
            file.transferTo(dest);
        } catch (IOException e) {
            e.printStackTrace();
            return new ResponseBodyMessage<>(102,"服务器上传失败！",false);
        }
        int indexDot=fileNameAndType.lastIndexOf(".");
        String title=fileNameAndType.substring(0,indexDot);
        User user=(User) httpSession.getAttribute(Constant.USERINFO_SESSION_KEY);
        int userid=user.getId();
        //        return new ResponseBodyMessage<>(101,"上传音乐失败！",false);
        //进行数据库的上传
        //1.播放音乐-->http请求
        String url="/music/get?path="+title;
        SimpleDateFormat sf=new SimpleDateFormat("yyy-MM-dd");
        String time=sf.format(new Date());

        try {
            //2. 先查询数据库当中 是否有当前音乐【歌曲名+歌手】
            Integer count= musicMapper.select(singer,title);
            int ret=0;
            if(count==null){
                 ret=musicMapper.insert(title,singer,url,time,userid);
            }else {
                return new ResponseBodyMessage<>(100,"当前音乐【歌曲名+歌手】已存在，请选择其他歌曲！",false);
            }
            if(ret==1){
                resp.sendRedirect("/list.html");
                return new ResponseBodyMessage<>(200,"数据库上传成功！",true);
            }else {
                return new ResponseBodyMessage<>(103,"数据库上传失败！",false);
            }
        }catch (BindingException | IOException e){
            dest.delete();
            return new ResponseBodyMessage<>(103,"数据库上传失败！",false);
        }
    }

    /**
     * 播放音乐的时候：/music/get?path=xxx.mp3
     * @param path
     * @return
     */
    @RequestMapping("/get")
    public ResponseEntity<byte[]> get(String path) {
        File file = new File(SAVE_PATH+"/"+path);
        byte[] a = null;
        try {
            a = Files.readAllBytes(file.toPath());
            if(a == null) {
                return ResponseEntity.badRequest().build();
            }
            return ResponseEntity.ok(a);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ResponseEntity.badRequest().build();
        //return ResponseEntity.internalServerError().build();
        //return ResponseEntity.notFound().build();
    }
    /**
     * @Author Sliqvers
     * @Description  删除单个音乐
     * @Param * @param[1] id
     * @Date 7:27 2025/5/22
     * @return * @return ResponseBodyMessage<Boolean>
     **/

    @RequestMapping("/delete")
    public ResponseBodyMessage<Boolean> deleteMusicById(@RequestParam String id){
        //1.先检查当前音乐是否存在
        int iid=Integer.parseInt(id);
        //2.如果存在：1. 删除数据库 2.删除服务器上的数据
        Music music=musicMapper.findMusicById(iid);
        if(music==null){
            return new ResponseBodyMessage<>(105,"没有你要删除的音乐",false);
        }else {
            //删除数据库
            int ret=musicMapper.deleteMusicById(iid);
            if(ret==1){
                //删除服务器上的数据
                int index=music.getUrl().lastIndexOf("=");
                String fileName = music.getUrl().substring(index + 1);
                File file=new File(SAVE_PATH+fileName+".mp3");
                System.out.println("当前的路径：" + file.getPath());
                if(file.delete()){
                    //同步删除lovemusic表当中的这个音乐
                    loveMusicMapper.deleteLoveMusicByMusicId(iid);
                    return new ResponseBodyMessage<>(200,"服务器当中的音乐删除成功！",true);
                }else {
                    return new ResponseBodyMessage<>(100,"服务器当中的音乐删除失败！",false);
                }

            }else {
                return new ResponseBodyMessage<>(106,"数据库当中的音乐没有删除成功！",false);
            }
        }
    }
    /**
     * @Author Sliqvers
     * @Description  批量删除
     * @Param * @param[1] null
     * @Date 5:40 2025/5/23
     * @return
     **/

    @RequestMapping("/deleteSel")
    public ResponseBodyMessage<Boolean> deleteSelMusic(@RequestParam("id[]") List<Integer>  id){
        System.out.println("所有的ID ： "+ id);
        int sum=0;
        for (int i = 0; i <id.size() ; i++) {
           int  musicId=id.get(i);
            Music music=musicMapper.findMusicById(musicId);
            if(music==null){
                return new ResponseBodyMessage<>(105,"没有你要删除的音乐",false);
            }
            int ret=musicMapper.deleteMusicById(musicId);
            if(ret==1){
                //删除服务器上的数据
                int index=music.getUrl().lastIndexOf("=");
                String fileName = music.getUrl().substring(index + 1);
                File file=new File(SAVE_PATH+fileName+".mp3");
              if(file.delete()){
                  //同步删除lovemusic表当中的这个音乐
                  loveMusicMapper.deleteLoveMusicByMusicId(musicId);
                  sum+=ret;
              }else {
                  return new ResponseBodyMessage<>(100,"服务器当中的音乐删除失败！",false);
              }
            }else {
                return new ResponseBodyMessage<>(100,"数据库当中的音乐删除失败！",false);
            }
        }
        if(sum==id.size()){
            System.out.println("整体删除成功");
            return new ResponseBodyMessage<>(200,"音乐删除成功！",true);
        }else {
            return new ResponseBodyMessage<>(100,"音乐删除失败！",false);
        }
    }
    @RequestMapping("/findmusic")
    public ResponseBodyMessage<List<Music>> findMusic(@RequestParam(required = false) String musicName) {

        List<Music> musicList = null;
        if(musicName != null) {
            musicList = musicMapper.findMusicByName(musicName);
        }else {
            musicList = musicMapper.findMusic();
        }
        return new ResponseBodyMessage<>(200,"查询到了所有的音乐",musicList);
    }
}
